package com.yjc.springcloud.controller;

import com.yjc.springcloud.bean.CommotResult;
import com.yjc.springcloud.bean.Payment;
import com.yjc.springcloud.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author shkstart
 * @create 2022-07-12 20:39
 */
@RestController
public class PaymentController {

    @Autowired
    PaymentService paymentService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/add/payment")
    public CommotResult addPayment(@RequestBody Payment payment) {
        int res = paymentService.addPayMent(payment);
        return res > 0 ? new CommotResult(200, "插入订单成功" + serverPort, res) :
                new CommotResult(444, "插入订单失败", null);
    }

    @GetMapping("/get/payment/{id}")
    public CommotResult<Payment> addPayment(@PathVariable("id") Long id) {
        Payment res = paymentService.getPaymentById(id);
        System.out.println(111);
        return res != null ? new CommotResult<Payment>(200, "成功查询到订单" + serverPort, res) :
                new CommotResult<Payment>(444, "未查询到该id订单", null);
    }

    @GetMapping("/payment/discovery")
    public Object discovery() {
        List<String> services = discoveryClient.getServices();
        for (String s : services) {
            System.out.println(s);
        }

        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance i : instances) {
            System.out.println(i.getServiceId() + ":" + i.getHost() + ":" + i.getPort() + ":" + i.getUri());
        }
        return this.discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String lb() {
        return serverPort;
    }

    @GetMapping("/payment/timeout")
    public String timeOut() {
        try {
            System.out.println("timeOut");
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

}
